package com.exchange.interceptor;

import com.exchange.common.model.User;
import com.exchange.constant.AppConst;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;

import cn.hutool.core.util.StrUtil;

public class AppUserTokenInterceptor implements Interceptor {
    public void intercept(Invocation inv) {
    	
        Controller c = inv.getController();
        System.out.println("token:"+c.getHeader("token"));
        System.out.println("account:"+c.getHeader("account"));
        
        if(StrUtil.isEmpty(c.getHeader("token"))) {
        	c.renderJson(Ret.fail("msg",EnumError.APP_USER_TOKEN_ERROR.getCode()));
        	return;
        }
        
        Cache rides = Redis.use(PropKit.get("redisName"));
        if(!rides.exists(c.getHeader("token"))) {
        	c.renderJson(Ret.fail("msg",EnumError.APP_USER_TOKEN_ERROR.getCode()));
        	return;
        }
        String account = rides.get(c.getHeader("token"));
        if(StrUtil.isEmpty(account) || !StrUtil.equals(account, c.getHeader("account"))) {
        	c.renderJson(Ret.fail("msg",EnumError.APP_USER_TOKEN_ERROR.getCode()));
        	return;
        }
        
        //往controller传数据
		User user = rides.get(account);
		c.setAttr("user", user);
		c.setAttr("token", c.getHeader("token"));
		c.setAttr("account", c.getHeader("account"));
        
        inv.invoke();
        
        //更新redis时间
        rides.expire(c.getHeader("token"), AppConst.USER_LOGIN_TIME);
        rides.expire(account, AppConst.USER_TIME);
        
    }

	

}
